//
//  HttpTool.m
//  TradeCloud
//
//  Created by zhangming on 2018/4/10.
//  Copyright © 2018年 zhangming. All rights reserved.
//

#import "HttpTool.h"
#import "HttpSessionManager.h"
#import "KF5SDK.h"
#import "LoginViewController.h"

//成功返回的标志
#define SuccessResponseCode 1

//网络回传失败域
#define ResponseFailureDomain @"ResponseFailureDomain"

@implementation HttpTool

+ (void)postUrlWithString:(NSString *)url parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    HttpSessionManager *manager = [HttpSessionManager shareManager];
    
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer.timeoutInterval = 120.f;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *token = [defaults objectForKey:@"token"];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDic = responseObject;
        
        if (success) {
            success(responseDic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
            [KFUserManager deleteUser];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                LoginViewController *LoVC = [[LoginViewController alloc]init];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                window.rootViewController= nav;
            });
            
            return;
        }
        
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)getUrlWithString:(NSString *)url parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    HttpSessionManager *manager = [HttpSessionManager shareManager];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer.timeoutInterval = 120.f;

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *token = [defaults objectForKey:@"token"];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authentication"];
    
    [manager GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDic = responseObject;
        
        if (success) {
            success(responseDic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
            [KFUserManager deleteUser];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                LoginViewController *LoVC = [[LoginViewController alloc]init];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                window.rootViewController= nav;
            });
            
            return;
        }
        
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)deleteUrlWithString:(NSString *)url parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    HttpSessionManager *manager = [HttpSessionManager shareManager];
    
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer.timeoutInterval = 120.f;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *token = [defaults objectForKey:@"token"];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    [manager DELETE:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDic = responseObject;
        
        if (success) {
            success(responseDic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
            [KFUserManager deleteUser];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                LoginViewController *LoVC = [[LoginViewController alloc]init];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                window.rootViewController= nav;
            });
            
            return;
        }
        
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)putUrlWithString:(NSString *)url parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    HttpSessionManager *manager = [HttpSessionManager shareManager];
    
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer.timeoutInterval = 120.f;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *token = [defaults objectForKey:@"token"];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    [manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDic = responseObject;
        
        if (success) {
            success(responseDic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
            [KFUserManager deleteUser];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                LoginViewController *LoVC = [[LoginViewController alloc]init];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                window.rootViewController= nav;
            });
            
            return;
        }
        
        if (failure) {
            failure(error);
        }
    }];
}

+ (NSError *)inspectError:(NSDictionary *)responseObject {
    
    if ([responseObject[@"msg"] isEqualToString:@"success"]) {
        
        return nil;
    } else {
        
        NSError *error = [NSError errorWithDomain:ResponseFailureDomain code:[responseObject[@"result"] integerValue] userInfo:@{NSLocalizedDescriptionKey:responseObject[@"msg"], NSLocalizedFailureReasonErrorKey:responseObject[@"msg"]}];
        return error;
    }
}

#pragma mark - 解析错误信息
+ (NSString *)handleError:(NSError *)error {
    if ([[error domain] isEqualToString:ResponseFailureDomain]) {
        
        return [error localizedDescription];
        
    } else {
        
        return @"网络错误，请检查您的网络配置";
    }
}

+(void)netWorkState:(void(^)(NSInteger status))block{
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    // 提示：要监控网络连接状态，必须要先调用单例的startMonitoring方法
    [manager startMonitoring];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        block(status);
    }];
}
@end
